package com.mayikt.utils;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @Classname RedisLockUtils
 * @Description SpringBoot SpringCloud 构建微服务电商平台。
 * @Created by CHEN JIN LONG
 * @Date 2019/1/22 23:15
 * @Version 1.0
 */

@Component
@Slf4j
public class RedisLockUtils {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final int ACQUIRETIMEOUT = 5 * 1000;//获取锁超时时间 10s

    private static final int TIMEOUT = 5 * 1000;//超时时间 10s


    /**
     * 加锁
     *
     * @param key   productId - 商品的唯一标志
     * @param value 当前时间+超时时间 也就是时间戳
     * @return
     */
    public boolean lock(String key, String value) {

        //String identifierValue = UUID.randomUUID().toString();
        int expireLock = (int) (TIMEOUT / 1000);
        Long endTime = System.currentTimeMillis() + ACQUIRETIMEOUT;
        //循环获取锁，获取锁超时时间
        while (System.currentTimeMillis() < endTime) {
            if (stringRedisTemplate.opsForValue().setIfAbsent(key, value)) {
                stringRedisTemplate.expire(key, expireLock, TimeUnit.SECONDS);
                return true;
            }
        }
        return false;
    }

    /**
     * 解锁
     *
     * @param key
     * @param value
     */
    public void unlock(String key, String value) {
        try {
            String currentValue = stringRedisTemplate.opsForValue().get(key);
            if (!StringUtils.isEmpty(currentValue) && currentValue.equals(value))
                //删除key
                stringRedisTemplate.opsForValue().getOperations().delete(key);
        } catch (Exception e) {
            log.error("[Redis分布式锁]解锁出现异常，{}", e);
        }
    }
}
